package lib

import (
	"RMS/app/shop/model"
	"RMS/common"
	"RMS/common/db"
	"context"
	"gorm.io/gorm"
	"log"
)

func ImplOrderList(ctx context.Context, req *model.OrderListReq) *model.OrderListResp {
	resp := &model.OrderListResp{}

	d := db.NewRmsDBRequest(ctx)
	d = d.Table(db.PmsOrderTable)

	orderListFilter(ctx, req, d)

	var total int64
	d.Count(&total)

	if req.PageSize != nil && req.PageIndex != nil {
		d.Offset((*req.PageIndex - 1) * *req.PageSize).Limit(*req.PageSize)
	}

	var data []map[string]interface{}
	if err := d.Find(&data).Error; err != nil && err != gorm.ErrRecordNotFound {
		log.Printf("ImplOrderList err := %v\n", err.Error())
		resp.Status = common.ErrCode
		resp.Message = common.FindErrMessage
		return resp
	}
	log.Println(data)

	resp.Status = common.SuccessCode
	resp.Message = common.SuccessMessage
	resp.Data = data
	resp.Total = int(total)
	return resp
}
func orderListFilter(ctx context.Context, req *model.OrderListReq, db *gorm.DB) {
	if req.Id != nil {
		db.Where("id = ?", *req.Id)
	}
	if req.StartTime != nil && req.EndTime != nil {
		db.Where("event_time between ? and ?", *req.StartTime, *req.EndTime)
	}
	db.Order("event_time desc")
}
